from django.shortcuts import render, redirect
from apps.web.forms.project import ProjectModelForm
from django.http import JsonResponse, HttpResponse
from apps.web import models
from tools import cos
import time
from pypinyin import pinyin


def project_list(request):
    """项目列表"""
    if request.method == 'GET':
        # 实例化对象
        form = ProjectModelForm(request)
        # get请求查看项目列表
        """
        1.从数据库获取两部分数据
            我创建的项目: 含已星标和未星标
            我参与的项目: 含已星标和未星标
        2.提取已星标的项目
            列表= 循环我创建的项目和我参与的项目得到一个列表
        """
        project_dict = {'star': [], 'my': [], 'join': []}
        # 我创建的项目
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({'value': row, 'type': 'my'})
            else:
                project_dict['my'].append(row)
        # 我参与的项目
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({'value': item.project, 'type': 'join'})
            else:
                project_dict['join'].append(item.project)
        return render(request, 'web/project_lsit.html', {'form': form, 'project_dict': project_dict})
    # post请求
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        name = form.cleaned_data.get('name')
        # 创建一个桶，和区域
        # 桶名称
        bucket = '{}-{}-{}-1360779007'.format(name, request.tracer.user.mobile_phone, str(int(time.time())))
        region = 'ap-chengdu'

        cos.create_cos(bucket, region)
        # 把桶写入数据库
        form.instance.bucket = bucket
        form.instance.region = region
        # 验证通过 modelForm中只添加了项目名，颜色，描述，需要加入创建者creator
        form.instance.creator = request.tracer.user
        # 创建项目
        instance = form.save()
        # 项目初始化问题类型
        for item in models.IssuesType.PROJECT_INIT_LIST:
            models.IssuesType.objects.create(project=instance, title=item)
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """项目星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')
    return HttpResponse('请求错误')


def project_unstar(request, project_type, project_id):
    """取消星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    return HttpResponse('请求错误')
